#include <stdio.h>

int main(){
    int n;
    scanf("%d",&n);
    int a[n];
    for (int i=0;i<n;i++){scanf("%d",&a[i]);}
    int position;
    int find=0;

    for (int j=n-1;j>0;j--){
        if (a[j-1]<a[j]){
            find=1;
            position=j-1;
            break;
        }
    }
    
    if (find==0){
        for (int i=0;i<n;i++){printf("%d",a[i]);if(i!=n-1)printf(" ");}
        return 0;
    }

    for (int i=n-1;i>position;i--){
        if (a[i]>a[position]){
            int temp=a[position];
            a[position]=a[i];
            a[i]=temp;
            break;
        }
    }
    

    for (int i=n-1;2*i>position+n-1;i--){
        int temp=a[i];
        a[i]=a[position+n-i];
        a[position+n-i]=temp;
    }
    for (int i=0;i<n;i++){printf("%d",a[i]);if(i!=n-1)printf(" ");}
    return 0;
}